@<template>
  <div>
    <!-- 面包屑导航区域 -->
    <breadcrumb :breadInfo="breadInfo" />

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesUser">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表展示区域 -->
      <el-table :data="rolesList" border style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="dbbottom" :class="[i1==0 ? 'dbtop': '']" v-for="(item,i1) in scope.row.children" :key="item.id"> 
              <!-- 一级权限 -->
              <el-col :span="5" >
                <el-tag closable @close="handleClose(scope.row,item.id)" >{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二级和三级权限区域 -->
              <el-col :span="19">
                
                <!-- 渲染二级权限 -->
                <el-row class="dbbottom" v-for="subItem in item.children" :key="subItem.id">
                  <el-col :span="6">
                    <el-tag closable @close="handleClose(scope.row,subItem.id)" type="success" >{{subItem.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 渲染三级权限 -->
                    <el-row   >
                      <el-tag closable @close="handleClose(scope.row,childItem.id)" v-for="childItem in subItem.children" :key="childItem.id" type="warning" > {{childItem.authName}}</el-tag>
                    </el-row>
                  </el-col>
                </el-row>

              </el-col>
            </el-row>
            
          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesUser(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRolesUser(scope.row)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRolesUser(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addUserDialogVisible"
      width="50%"

      @close="closeDialog">
      
       <!-- 添加内容区域 -->
      <el-form
        :model="addRolesUserForm"
        :rules="addRolesUserFormRules"
        ref="addRolesUserFormRef"
        label-width="80px"
        
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesUserHandler">确 定</el-button>
      </span>
      
    </el-dialog>

        <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editUserDialogVisible"
      width="50%"

      @close="closeDialog">
      
       <!-- 添加内容区域 -->
      <el-form
        :model="editRolesUserForm"
        :rules="addRolesUserFormRules"
        ref="editRolesUserFormRef"
        label-width="80px"
        
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesUserHandler">确 定</el-button>
      </span>
      
    </el-dialog>

    <!-- 权限树 对话框 -->
    <el-dialog
    title="权限分配"
    :visible.sync="setRolesUserDialogVisible"
    width="50%"
    @close="closeDialog"
    >
    <el-tree show-checkbox node-key="id" 
    default-expand-all 
    :default-checked-keys="defaultKeys" 
    :data="rolesTree" 
    :props="rolesTreeProps" 
    ref="roleTreeRef"
    ></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRolesUserDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setRolesUserhandler">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../../common/breadcrumb/Breadcrumb.vue";
export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      breadInfo: ["权限管理", "角色列表"],
      rolesList: [],
      addUserDialogVisible: false,
      addRolesUserForm:{
        roleName: '',
        roleDesc: ''
      },
    
      addRolesUserFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称!', trigger: 'blur'}
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur'}
        ]
      },
        editRolesUserForm: {

      },
      editUserDialogVisible: false,
      setRolesUserDialogVisible: false,
      rolesTree: [], //权限树 
      rolesTreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件 默认选中的节点
      defaultKeys: [],
      roleId: '',
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 请求角色列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("请求角色数据失败");

      this.rolesList = res.data;
    },
    // 删除三级权限
    handleClose(rowInfo, rightId){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
          // 发起删除权限 网络请求
          
          const {data: res} = await this.$http.delete(`roles/${rowInfo.id}/rights/${rightId}`)
          if (res.meta.status !== 200) return this.$message.error("删除失败!")
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 删除成功,重新获取数据,重新赋值
          rowInfo.children = res.data
          // this.getRolesList() 
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        })
    },
    // 添加角色按钮
    addRolesUser() {
      this.addUserDialogVisible = true
    },
    // 添加对话框 关闭事件处理函数
    closeDialog() {
      // 重置表单
      this.$refs.addRolesUserFormRef?.resetFields()
      this.$refs.editRolesUserFormRef?.resetFields()
      this.defaultKeys = []
    },
    // 确认添加用户按钮
    addRolesUserHandler() {
      // 预验证表单
      this.$refs.addRolesUserFormRef.validate(async valid => {
        if (!valid) return 

        // 通过验证后, 发送添加角色网络请求
        const {data: res} = await this.$http.post('roles', this.addRolesUserForm)
        if (res.meta.status !== 201) return this.$message.error("添加权限角色失败")
        this.$message.success("添加成功")
        this.getRolesList()
        // 关闭对话框
        this.addUserDialogVisible = false
      })
    },
    // 编辑权限用户
    async editRolesUser(rowInfo) {
      // 获取权限用户数据
      const {data: res} = await this.$http.get(`roles/${rowInfo.id}`)
      // 保存获取到的权限用户数据
      this.editRolesUserForm = res.data

      // 展示添加用户对话框
      this.editUserDialogVisible = true
    },
    // 确认修改按钮
    editRolesUserHandler() {
      // 表单预验证
      this.$refs.editRolesUserFormRef.validate(async valid => {
        if (!valid) return 

        // 验证通过, 发送修改请求
        const {data: res}  = await this.$http.put(`roles/${this.editRolesUserForm.roleId}`, this.editRolesUserForm)
        if (res.meta.status !== 200) return this.$message.error("修改失败")

        this.$message.success("修改成功")
        this.getRolesList()
        this.editUserDialogVisible = false
      })
    },
    // 删除权限用户
    deleteRolesUser(rowInfo) {
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
        //  发送请求, 删除权限用户
          const {data: res} = await this.$http.delete(`roles/${rowInfo.id}`)
          if (res.meta.status !== 200) return this.$message.error("删除失败!")
          this.getRolesList()
          this.$message({
            
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 设置权限用户
    async setRolesUser(rowInfo) {
      // 获取所有权限数据
      const {data: res} = await this.$http.get(`rights/tree`)
      if (res.meta.status !== 200) return this.$message.error("权限列表请求失败")
      this.rolesTree = res.data
      this.roleId = rowInfo.id
      // 将id 添加到默认选中数组
      rowInfo.children.forEach(item1 => {
        item1.children.forEach(item2 => {
          item2.children.forEach(item3 => {
            this.defaultKeys.push(item3.id)
          }) 
        })
      })

      this.setRolesUserDialogVisible = true
    },
    // 点击确认分配权限 按钮
    async setRolesUserhandler() {
      // 获取 已选中和 半选中的id 并合并为一个数组
      const idArr = [
        ...this.$refs.roleTreeRef.getCheckedKeys(),
        ...this.$refs.roleTreeRef.getHalfCheckedKeys()
      ]
      // 将数组 转换为 以 逗号分割的 字符串 , 后端要求的
      const idStr = idArr.join(',')

      // 发送分配权限的请求
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids:idStr})
      if(res.meta.status !== 200) return this.$message.error("权限更新失败")
      
      this.$message.success("权限更新成功")

      // 重新获取数据
      this.getRolesList()

      // 关闭对话框
      this.setRolesUserDialogVisible = false

    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin:15px;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.dbtop {
  border-top: 1px solid #eee;
}

.el-row {
  display: flex;
  align-items: center;
}
</style>